package com.ytjj.qmyx.mall.controller;

import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.OrderUtils;
import com.ytjj.qmyx.mall.constants.RedisConstants;
import com.ytjj.qmyx.mall.model.vo.ChannelVO;
import com.ytjj.qmyx.mall.service.CommonService;
import com.ytjj.qmyx.mall.service.SkipStatisticsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


/**
 * 
 * @version 1.0
 *
 */
@Controller
@RefreshScope
public class SkipURLController {

    private final static String COOKIE_NAME = "usersAccount";

    @Autowired
    private SkipStatisticsService skipStatisticsService;

    @Resource
    private RedisService redisService;

    @Resource
    private CommonService commonService;

    @Value("${longExpireChannel:}")
    private String longExpireChannel;

    @Value("${channelSkip:0}")
    private String channelSkip;

    public void redirect(HttpServletRequest request,
                         HttpServletResponse response,String channel, String uri) throws IOException {
        String redirect = "https://kq..com/pages/home/home.html?channel="+channel;
        String usersAccount = addCookies(request, response);
        boolean exist = redisService.hashKey(RedisConstants.CHANNEL, channel);
        if(exist) {
            redirect = redisService.getMapString(RedisConstants.CHANNEL, channel);
        }

        if(StringUtils.isNotEmpty(request.getQueryString())){
            redirect = redirect+"&"+request.getQueryString();
        }
        skipStatisticsService.saveSkipStatistics(uri, usersAccount, channel);
        redirect = redirect +"&_referer=https://t..com/channelRedirect/"+uri+"/"+channel;
//        try {
//            ChannelVO channelVO=commonService.findChannel(channel);
//            if(channelVO!=null&&(channelVO.getChannel().startsWith("ht")||channelVO.getChannel().startsWith("wei"))){
//                Calendar cal = Calendar.getInstance();
//                List<String> longExpireChannelList=new ArrayList<>();
//                if(longExpireChannelList.isEmpty()) {
//                    if (org.apache.commons.lang.StringUtils.isNotBlank(longExpireChannel)) {
//                        String[] longExpireChannelArray = longExpireChannel.split(",");
//                        for (String str : longExpireChannelArray) {
//                            longExpireChannelList.add(str);
//                        }
//                    }
//                }
//                if(longExpireChannelList.contains(channel)){
//                    cal.add(Calendar.DATE, -15);
//                }else {
//                    cal.add(Calendar.DATE, -10);
//                }
//                if("ht-sms-99".equals(channel)){
//                    cal.add(Calendar.DATE, -30);
//                }
//                if("jx-sms-630".equals(channel)){
//                    cal.add(Calendar.DATE, -10);
//                }
//                if("ht-sms-150".equals(channel)||"jx-sms-658".equals(channel)||"ygyx-gbh5-11".equals(channel)||"ygyx-gbh5-12".equals(channel)
//                    ||"ygyx-gbh5-13".equals(channel)||"ygyx-gbh5-15".equals(channel)||"jx-sms-702".equalsIgnoreCase(channel)
//                        ||"jx-sms-699".equalsIgnoreCase(channel)||"jx-sms-710".equalsIgnoreCase(channel)
//                        ||"jx-sms-711".equalsIgnoreCase(channel)||"jx-sms-800".equalsIgnoreCase(channel)
//                        ||"jx-sms-801".equalsIgnoreCase(channel)){//长期有效
//                    cal.add(Calendar.DATE, -300);
//                }
//                if(channelVO.getCreateTime()!=null&& channelVO.getCreateTime().compareTo(cal.getTime())<0){
//                    //response.sendError(404);
//                    response.sendRedirect("https://h5..cn/components/productItem/down/down.html?channel="+channel);
//                    return;
//                }
//            }
//            if("1".equals(channelSkip)){//强制跳转到首页
//                response.sendRedirect("https://h5..cn/pages/home/home.html?channel="+channel);
//                return;
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }
        response.sendRedirect(redirect);
    }

    public String addCookies(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        String usersAccount = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (COOKIE_NAME.equals(cookie.getName())) {
                    usersAccount = cookie.getValue();
                }
            }
        }
        if (null == usersAccount) {
            usersAccount = OrderUtils.getRandomAccount();
            Cookie cookie = new Cookie(COOKIE_NAME, usersAccount);
            response.addCookie(cookie);
        }

        return usersAccount;
    }

    /**
     * 渠道跳转链接
     *
     * @param channel
     * @param uri
     * @param request
     * @param response
     */
    @RequestMapping("/channelRedirect/{uri}/{channel}")
    public void redirectUrl(@PathVariable("channel") String channel, @PathVariable("uri") String uri, HttpServletRequest request, HttpServletResponse response) throws IOException {
        redirect(request,response,channel,uri);
    }

}
